﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TowerDefense.ToolKit
{
    /// <summary>
    /// I Keep all dead objects! >_>
    /// Ask me for one and you might receive
    /// </summary>
    public class Graveyard
    {
        private static Dictionary<Type, List<Object>> graveyard = null;
        private static Graveyard self;

        public Graveyard()
        {
            if (graveyard == null)
                graveyard = new Dictionary<Type, List<object>>();
        }

        /// <summary>
        /// Lurk graveyard for bodys that look like T
        /// </summary>
        /// <typeparam name="T">Generic</typeparam>
        /// <returns>T</returns>
        public Boolean Search<T>()
        {
            return graveyard.ContainsKey(typeof(T));
        }

        /// <summary>
        /// I will return a dead body if I got one.
        /// Make sure to reset it!
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public T Raise<T>()
        {
            T corpse = default(T);
            if (!graveyard.ContainsKey(typeof(T)) || graveyard[typeof(T)].Count == 0)
                return corpse;

            T result = (T)graveyard[typeof(T)][0];
            graveyard[typeof(T)].Remove(result);

            return result;
        }
        
        /// <summary>
        /// I help you bury dead bodies.
        /// But you have to kill it yourself!
        /// </summary>
        /// <typeparam name="T">What kind of body is it?</typeparam>
        /// <param name="killedObj">The dead body</param>
        public void Bury<T>(T killedObj)
        {
            if (graveyard.ContainsKey(typeof(T)))
            {
                graveyard[typeof(T)].Add(killedObj);
            }
            else
            {
                List<Object> list = new List<Object> {killedObj};
                graveyard.Add(typeof(T), list);
            }
        }


        internal int GraveYardDeeph
        {
            get
            {
                Int32 totalCount = 0;
                foreach (KeyValuePair<Type, List<object>> pair in graveyard)
                {
                    totalCount += pair.Value.Count;
                }

                return totalCount;
            }
        }

        internal static int GraveYardDeephByType(Type type)
        {
            if (!graveyard.ContainsKey(type)) //No burried item
                return 0;

            return graveyard[type].Count;
        }
    }
}